import axios from "axios";
import store from "@/store";
import router from "@/router";
import qs from "qs";
import { Loading, Message } from "element-ui";
import { getToken } from "@/utils/auth";

let channel, agent;
if (
  window.location.hostname == "localhost" ||
  window.location.hostname.indexOf("192.168") > -1
) {
  channel = "testzhu";
  agent = "";
} else {
  const hostArr = window.location.host.split(".");
  if (hostArr.length == 5) {
    agent = hostArr[0];
    channel = hostArr[1];
  } else if (hostArr.length == 4) {
    agent = "";
    channel = hostArr[0];
  }
}

store.commit("UPDATE_CHANNEL_INFO", { channel, agent });

// 创建axios实例
const service = axios.create({
  withCredentials: true,
  timeout: 6000, // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers["token"] = getToken();
    }
    return config;
  },
  (error) => {
    console.log("service.interceptors error =>", error);
    Promise.reject(error);
  }
);

// response拦截器
service.interceptors.response.use(
  (response) => {
    tryHideFullScreenLoading();
    if (response.data.code == "401") {
      store.commit("SET_TOKEN", {
        token: "",
      });

      store.commit("SET_ISLOGIN", {
        isLogin: false,
      });

      store.commit("UPDATE_USER_INFO", {});

      store.commit("UPDATE_LOGOUT");
    }
    if (!response.data.success) {
      if (
        response.data.code != "401" &&
        response.data.message &&
        response.data.code != "40009"
      ) {
        Message.error(response.data.message);
      }
    }
    return response;
  },
  (error) => {
    tryHideFullScreenLoading();
    let msg = error.message || "网络繁忙，请稍后再试";
    if (msg.indexOf("timeout") > -1) {
      msg = "网络繁忙，请稍后再试";
    }
    Message.error(msg);
    return Promise.reject(error);
  }
);

let loading; //定义loading变量

function startLoading() {
  //使用Element loading-start 方法
  loading = Loading.service({
    lock: true,
    text: "加载中",
    background: "rgba(0, 0, 0, 0)",
  });
}

function endLoading() {
  //使用Element loading-close 方法
  loading.close();
}

let needLoadingRequestCount = 0;

export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
}

export function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
}

/**
 * 封装get方法
 * @param url
 * @param params
 * @returns {Promise<any>}
 */

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params: params,
      })
      .then((response) => {
        if (response.data.success) {
          return resolve(response.data);
        } else {
          return reject(response.data);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @param isFormData
 * @returns {Promise}
 */

export function post(url, data = {}, isFormData) {
  let POST_FORM_OPTION = {
    transformRequest: [
      function (data) {
        return qs.stringify(data);
      },
    ],
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
  };
  return new Promise((resolve, reject) => {
    service.post(url, data, isFormData ? POST_FORM_OPTION : {}).then(
      (response) => {
        if (response.data.success) {
          return resolve(response.data);
        } else {
          return reject(response.data);
        }
      },
      (err) => {
        reject(err);
      }
    );
  });
}
